

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Blue~u~u~u">
  <meta name="author" content="Blue~u~u~u">
  <meta name="keywords" content="">
  <meta name="description" content="代理模式基本介绍： 代理模式：为一个对象提供一个替身，以控制对这个对象的访问(被代理的对象)。即通过代理对象访问目标对象，这样的好处是可以再目标对象实现的基础上，增强额外的功能操作，即扩展目标对象的功能。 被代理的对象可以是远程对象、创建开销大的对象或者需要安全控制的对象 代理模式有三种不同的形式，主要有三种  静态代理  动态代理(JDK代理，接口代理)  Cglib代理(可以再内存动态的创建对">
<meta property="og:type" content="article">
<meta property="og:title" content="java设计模式-代理模式">
<meta property="og:url" content="http://www.slx.blue/2021/12/06/java-Proxy/index.html">
<meta property="og:site_name" content="Blue~u~u~u~u">
<meta property="og:description" content="代理模式基本介绍： 代理模式：为一个对象提供一个替身，以控制对这个对象的访问(被代理的对象)。即通过代理对象访问目标对象，这样的好处是可以再目标对象实现的基础上，增强额外的功能操作，即扩展目标对象的功能。 被代理的对象可以是远程对象、创建开销大的对象或者需要安全控制的对象 代理模式有三种不同的形式，主要有三种  静态代理  动态代理(JDK代理，接口代理)  Cglib代理(可以再内存动态的创建对">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/Proxy/staticProxy.png">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/Proxy/dynamic.png">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/Proxy/cglib.png">
<meta property="article:published_time" content="2021-12-06T13:48:08.000Z">
<meta property="article:modified_time" content="2022-01-16T11:08:53.061Z">
<meta property="article:author" content="Blue~u~u~u">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/Proxy/staticProxy.png">
  
  <title>java设计模式-代理模式 - Blue~u~u~u~u</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.slx.blue","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":180,"cursorChar":"_","loop":true},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>

<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
<script src="/live2d-widget/autoload.js"></script>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Blue~u~u</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="java设计模式-代理模式">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-12-06 21:48" pubdate>
        2021年12月6日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.7k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      18 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">java设计模式-代理模式</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：4 个月前
                
              </p>
            
            <div class="markdown-body">
              <h3 id="代理模式"><a href="#代理模式" class="headerlink" title="代理模式"></a>代理模式</h3><h4 id="基本介绍："><a href="#基本介绍：" class="headerlink" title="基本介绍："></a>基本介绍：</h4><ol>
<li>代理模式：为一个对象提供一个替身，以控制对这个对象的访问(被代理的对象)。即通过代理对象访问目标对象，这样的好处是可以再目标对象实现的基础上，增强额外的功能操作，即扩展目标对象的功能。</li>
<li>被代理的对象可以是远程对象、创建开销大的对象或者需要安全控制的对象</li>
<li>代理模式有三种不同的形式，主要有三种 <ul>
<li><strong>静态</strong>代理 </li>
<li><strong>动态</strong>代理(<code>JDK</code>代理，接口代理) </li>
<li><code>Cglib</code>代理(可以再内存动态的创建对象，而不需要实现接口，属于<strong>动态代理</strong>的范畴)</li>
</ul>
</li>
</ol>
<h4 id="1-静态代理"><a href="#1-静态代理" class="headerlink" title="1.静态代理"></a>1.静态代理</h4><p>静态代理在使用时，需要定义接口或者父类(即目标对象)与代理对象一起实现相同的接口或者是继承相同父类</p>
<p>用例图：</p>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/Proxy/staticProxy.png" srcset="/img/loading.gif" lazyload alt="image"></p>
<p>代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//接口</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ITeacherDao</span> </span>&#123;<br>	<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">teach</span><span class="hljs-params">()</span></span>; <span class="hljs-comment">// 授课的方法</span><br>&#125;<br><br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//实现方法</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TeacherDao</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ITeacherDao</span> </span>&#123;<br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">teach</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot; 老师授课中  。。。。。&quot;</span>);<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//代理对象,静态代理</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TeacherDaoProxy</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ITeacherDao</span></span>&#123;<br>	<br>	<span class="hljs-keyword">private</span> ITeacherDao target; <span class="hljs-comment">// 目标对象，通过接口来聚合</span><br>	<span class="hljs-comment">//构造器</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TeacherDaoProxy</span><span class="hljs-params">(ITeacherDao target)</span> </span>&#123;<br>		<span class="hljs-keyword">this</span>.target = target;<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">teach</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;开始代理  完成某些操作。。。。。 &quot;</span>);<span class="hljs-comment">//方法</span><br>		target.teach();<br>		System.out.println(<span class="hljs-string">&quot;提交。。。。。&quot;</span>);<span class="hljs-comment">//方法</span><br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//客户端</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>&#123;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>		<span class="hljs-comment">//创建目标对象(被代理对象)</span><br>		TeacherDao teacherDao = <span class="hljs-keyword">new</span> TeacherDao();<br>		<br>		<span class="hljs-comment">//创建代理对象, 同时将被代理对象传递给代理对象</span><br>		TeacherDaoProxy teacherDaoProxy = <span class="hljs-keyword">new</span> TeacherDaoProxy(teacherDao);<br>		<br>		<span class="hljs-comment">//通过代理对象，调用到被代理对象的方法</span><br>		<span class="hljs-comment">//即：执行的是代理对象的方法，代理对象再去调用目标对象的方法 </span><br>		teacherDaoProxy.teach();<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>静态代理优缺点：</p>
<ol>
<li>优点‘：在不修改目标对象的功能前提下，能通过代理对象对目标功能进行扩展</li>
<li>缺点：因为代理对象需要与目标对象实现一样的接口，所以会有很多代理类</li>
<li>一旦接口增加方法，目标对象与代理对象都要维护</li>
</ol>
<h4 id="2-动态代理"><a href="#2-动态代理" class="headerlink" title="2.动态代理"></a>2.动态代理</h4><p>基本介绍</p>
<ol>
<li>代理对象，不需要实现接口，但是目标对象要实现接口，否则不能用动态代理</li>
<li>代理对象的生成，是利用<code>JDK</code>的<code>API</code>，动态的在内存中构建代理对象</li>
<li>动态代理也叫：<code>JDK</code>代理，接口代理</li>
</ol>
<p><code>JDK</code>中生成代理对象的<code>API</code></p>
<ol>
<li><p>代理类所在包：<code>java.lang.reflect.Proxy</code></p>
</li>
<li><p><code>JDK</code>实现代理类只需要使用<code>newProxyInstance</code>方法，但是该方法需要接收三个参数，完整方法为</p>
</li>
</ol>
<blockquote>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs delphi">&gt;<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">Object</span> newProxyInstance(<br>&gt;ClassLoader loader,<br>&gt;<span class="hljs-keyword">Class</span>&lt;?&gt;[] interfaces,<br>&gt;InvocationHandler h)<br></code></pre></td></tr></table></figure>
</blockquote>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/Proxy/dynamic.png" srcset="/img/loading.gif" lazyload alt="dynamic"></p>
<p>代码实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//接口</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ITeacherDao</span> </span>&#123;<br>	<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">teach</span><span class="hljs-params">()</span></span>; <span class="hljs-comment">// 授课方法</span><br>	<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sayHello</span><span class="hljs-params">(String name)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//实现类</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TeacherDao</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ITeacherDao</span> </span>&#123;<br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">teach</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot; 老师授课中.... &quot;</span>);<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sayHello</span><span class="hljs-params">(String name)</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;hello &quot;</span> + name);<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProxyFactory</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br><br>    <span class="hljs-comment">//目标对象 , Object</span><br>    <span class="hljs-keyword">private</span> T target;<br><br>    <span class="hljs-comment">//构造器传入 ， 对target 进行初始化</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ProxyFactory</span><span class="hljs-params">(T target)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.target = target;<br>    &#125;<br><br>    <span class="hljs-comment">//给目标对象 生成一个代理对象</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">getProxyInstance</span><span class="hljs-params">()</span> </span>&#123;<br><br>        <span class="hljs-comment">//说明</span><br>		<span class="hljs-comment">/*</span><br><span class="hljs-comment">		 *  public static Object newProxyInstance(ClassLoader loader,</span><br><span class="hljs-comment">                                          Class&lt;?&gt;[] interfaces,</span><br><span class="hljs-comment">                                          InvocationHandler h)</span><br><span class="hljs-comment">                                          </span><br><span class="hljs-comment">            //1. ClassLoader loader ： 指定当前目标对象使用的类加载器, 获取加载器的方法固定</span><br><span class="hljs-comment">            //2. Class&lt;?&gt;[] interfaces: 目标对象实现的接口类型，使用泛型方法确认类型</span><br><span class="hljs-comment">            //3. InvocationHandler h : 事情处理，执行目标对象的方法时，会触发事情处理器方法,</span><br><span class="hljs-comment">            // 会把当前执行的目标对象方法作为参数传入</span><br><span class="hljs-comment">		 */</span><br>        <span class="hljs-keyword">return</span> (T) Proxy.newProxyInstance(<br>                target.getClass().getClassLoader(),  <span class="hljs-comment">//构建代理对象的类加载器 反射</span><br>                target.getClass().getInterfaces(),<br>                <span class="hljs-keyword">new</span> InvocationHandler() &#123;<br>                    <span class="hljs-meta">@Override</span><br>                    <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">invoke</span><span class="hljs-params">(Object proxy,</span></span><br><span class="hljs-params"><span class="hljs-function">                                         Method method, </span></span><br><span class="hljs-params"><span class="hljs-function">                                         Object[] args)</span> <span class="hljs-keyword">throws</span> Throwable </span>&#123;<br>                        <span class="hljs-comment">//invoke方法的作用是执行具体的代理逻辑 </span><br>                        <span class="hljs-comment">//也就是代理对象调用任意方法都会执行invoke</span><br>                        <span class="hljs-comment">//参数一 proxy: 代理对象本身</span><br>                        <span class="hljs-comment">//参数二 method : 代理对象调用的方法</span><br>                        <span class="hljs-comment">//参数三 args : 代理对象调用方法时传入的参数</span><br>                        <span class="hljs-comment">//返回值表示代理对象调用方法所受到的返回值</span><br>                        <span class="hljs-comment">//此时创建的代理对象可以代理任意借口 如果想只代理对应方法</span><br>                        String name = method.getName();<br>                        <span class="hljs-comment">//可以获取代理对象的方法名做if判断 进行核心逻辑判断 是否要代理</span><br>                        <span class="hljs-keyword">if</span> (!name.equals(<span class="hljs-string">&quot;&quot;</span>))&#123;<br>                            System.out.println(<span class="hljs-string">&quot;执行了对应方法&quot;</span>);<br>                            System.out.println(<span class="hljs-string">&quot;方法执行前 代理开始了 &quot;</span>);<br>                            <span class="hljs-comment">//反射机制调用目标对象的方法</span><br>                            Object returnVal = method.invoke(target, args);<br>                            System.out.println(<span class="hljs-string">&quot;方法执行后 代理又开始了&quot;</span>);<br>                            <span class="hljs-keyword">return</span> returnVal;<br>                        &#125;<br>                        <span class="hljs-comment">//方法不需要代理</span><br>                        <span class="hljs-keyword">return</span> method.invoke(target,args);<br>                    &#125;<br>                &#125;);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//客户端</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>&#123;<br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>		<span class="hljs-comment">//创建目标对象</span><br>		ITeacherDao target = <span class="hljs-keyword">new</span> TeacherDao();<br>		<br>		<span class="hljs-comment">//给目标对象，创建代理对象, 可以转成 ITeacherDao</span><br><span class="hljs-comment">//		ProxyFactory&lt;ITeacherDao&gt; factory = new ProxyFactory&lt;&gt;(target);</span><br><span class="hljs-comment">//		ITeacherDao proxyInstanceDao = factory.getProxyInstance();</span><br><br>		ITeacherDao proxyInstance = <br>            <span class="hljs-keyword">new</span> ProxyFactory&lt;ITeacherDao&gt;(target).getProxyInstance();<span class="hljs-comment">//直接获取代理对象</span><br><br>		<span class="hljs-comment">// proxyInstance=class com.sun.proxy.$Proxy0 内存中动态生成了代理对象</span><br>		System.out.println(<span class="hljs-string">&quot;proxyInstance=&quot;</span> + proxyInstance.getClass());<br>		<br>		<span class="hljs-comment">//通过代理对象，调用目标对象的方法</span><br>		<span class="hljs-comment">//proxyInstance.teach();</span><br>		proxyInstance.sayHello(<span class="hljs-string">&quot; 龙龙龙 &quot;</span>);<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="3-Cglib代理"><a href="#3-Cglib代理" class="headerlink" title="3.Cglib代理"></a>3.Cglib代理</h4><p>基本介绍：</p>
<ol>
<li><p>静态代理和<code>JDK</code>代理模式都要求目标对象是实现一个接口,但是有时候目标对象只是一个单独的对象,并没有实<br>现任何的接口,这个时候可使用目标对象子类来实现代理-这就是<code>Cglib</code>代理</p>
</li>
<li><p>Cglib代理也叫作子类代理,它是在内存中构建一个子类对象从而实现对目标对象功能扩展，有些书也将Cglib代<br>理归属到动态代理。</p>
</li>
<li><p><code>Cglib</code>是一个强大的高性能的代码生成包,它可以在运行期扩展<code>java</code>类与实现<code>java</code>接口.它广泛的被许多<code>AOP</code>的<br>框架使用,例如Spring <code>AOP</code>，实现方法拦截</p>
</li>
<li><p>在<code>AOP</code>编程中如何选择代理模式:</p>
<ul>
<li>目标对象需要实现接口，用<code>JDK</code>代理</li>
<li>目标对象不需要实现接口，用<code>Cglib</code>代理</li>
</ul>
</li>
<li><p><code>Cglib</code>包的底层是通过使用字节码处理框架<code>ASM</code>来转换字节码并生成新的类</p>
</li>
</ol>
<p>设计类图：</p>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/Proxy/cglib.png" srcset="/img/loading.gif" lazyload alt="dynamic"></p>
<p>代码实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//被代理对象</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TeacherDao</span> </span>&#123;<br>	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">teach</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot; 老师授课中  ， 我是cglib代理，不需要实现接口 &quot;</span>);<br>		<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;hello&quot;</span>;<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//代理工厂</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProxyFactory</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">MethodInterceptor</span> </span>&#123;<br><br>	<span class="hljs-comment">//维护一个目标对象</span><br>	<span class="hljs-keyword">private</span> Object target;<br>	<br>	<span class="hljs-comment">//构造器，传入一个被代理的对象</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ProxyFactory</span><span class="hljs-params">(Object target)</span> </span>&#123;<br>		<span class="hljs-keyword">this</span>.target = target;<br>	&#125;<br><br>	<span class="hljs-comment">//返回一个代理对象:  是 target 对象的代理对象</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">getProxyInstance</span><span class="hljs-params">()</span> </span>&#123;<br>		<span class="hljs-comment">//1. 创建一个工具类</span><br>		Enhancer enhancer = <span class="hljs-keyword">new</span> Enhancer();<br>		<span class="hljs-comment">//2. 设置父类</span><br>		enhancer.setSuperclass(target.getClass());<br>		<span class="hljs-comment">//3. 设置回调函数</span><br>		enhancer.setCallback(<span class="hljs-keyword">this</span>);<br>		<span class="hljs-comment">//4. 创建子类对象，即代理对象</span><br>		<span class="hljs-keyword">return</span> enhancer.create();<br>	&#125;<br>	<br>	<span class="hljs-comment">//重写  intercept 方法，会调用目标对象的方法</span><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">intercept</span><span class="hljs-params">(Object arg0,</span></span><br><span class="hljs-params"><span class="hljs-function">                            Method method, </span></span><br><span class="hljs-params"><span class="hljs-function">                            Object[] args, </span></span><br><span class="hljs-params"><span class="hljs-function">                            MethodProxy arg3)</span> <span class="hljs-keyword">throws</span> Throwable </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;Cglib代理模式 ~~ 开始&quot;</span>);<br>		Object returnVal = method.invoke(target, args);<br>		System.out.println(<span class="hljs-string">&quot;Cglib代理模式 ~~ 提交&quot;</span>);<br>		<span class="hljs-keyword">return</span> returnVal;<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//客户端</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>&#123;<br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>		<span class="hljs-comment">//创建目标对象</span><br>		TeacherDao target = <span class="hljs-keyword">new</span> TeacherDao();<br>		<span class="hljs-comment">//获取到代理对象，并且将目标对象传递给代理对象</span><br>		TeacherDao proxyInstance = (TeacherDao)<span class="hljs-keyword">new</span> ProxyFactory(target).getProxyInstance();<br><br>		<span class="hljs-comment">//执行代理对象的方法，触发intecept 方法，从而实现 对目标对象的调用</span><br>		String res = proxyInstance.teach();<br>		System.out.println(<span class="hljs-string">&quot;res=&quot;</span> + res);<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="4-其他变体"><a href="#4-其他变体" class="headerlink" title="4.其他变体"></a>4.其他变体</h4><p>几种常见的代理模式介绍一几种变体</p>
<ol>
<li>防火墙代理：内网通过代理穿透防火墙，实现对公网的访问。</li>
<li>缓存代理：比如 当请求图片文件等资源时，先到缓存代理取，如果取到资源则ok,如果取不到资源，再到公网或者数据库取，然后缓存。</li>
<li>远程代理：远程对象的本地代表，通过它可以把远程对象当本地对象来调用。远程代理通过网络和真正的远程对象沟通信息。</li>
<li>同步代理:主要使用在多线程编程中，完成多线程间同步工作</li>
</ol>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/designMode/">designMode</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客目前大部分文章都是参考尚硅谷或者马士兵教育的学习资料！<a href="http://www.atguigu.com/" rel="nofollow noopener"官网地址！</a> 
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/12/07/spring-day03-AOP/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">spring-day03-AOP</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/12/06/java-singleton/">
                        <span class="hidden-mobile">java设计模式-单例模式</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">

  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
	<!--《添加网站运行时间 -->
<br/>

<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
var now = new Date(); 

function createtime() {
    //此处修改你的建站时间或者网站上线时间
    var grt = new Date('11/02/2021 21:39:00');
    now.setTime(now.getTime() + 250);
    days = (now - grt) / 1000 / 60 / 60 / 24;

    dnum = Math.floor(days);
    hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
    hnum = Math.floor(hours);
    if (String(hnum).length == 1) {
        hnum = "0" + hnum;
    }
    minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes);
    if (String(mnum).length == 1) {
        mnum = "0" + mnum;
    }
    seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds);
    if (String(snum).length == 1) {
        snum = "0" + snum;
    }
    document.getElementById("timeDate").innerHTML = " 本站已各种夹缝中安全运行 " + dnum + " 天 ";
    document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
}
setInterval("createtime()", 250);
</script>

<!-- 添加网站运行时间》-->
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
